#!/usr/bin/env python3
#-*-encoding:utf-8-*-
# auther： Join.Rambo
# 使用python打包
#coding=utf-8
import subprocess,os,shutil, time

# 部署的时候修改_new_str版本号即可 编译命令 python .\complie.py
_new_str="v20220209"
_old_str="${currVersion}"
_base_workspace="E:/Users/lambert/git/assassination2_1/"
#替换文件内容
def alter(file,old_str,new_str):
    """
    替换文件中的字符串
    :param file:文件名
    :param old_str:就字符串
    :param new_str:新字符串
    :return:
    """
    file_data = ""
    with open(file, "r", encoding="utf-8") as f:
        for line in f:
            if old_str in line:
                line = line.replace(old_str,new_str)
            file_data += line
    with open(file,"w",encoding="utf-8") as f:
        f.write(file_data)
#copy文件
def mycopyfile(srcfile,dstfile):
    if not os.path.isfile(srcfile):
        print (srcfile+" not exist!")
    else:
        fpath,fname=os.path.split(dstfile)    #分离文件名和路径
        if not os.path.exists(fpath):
            os.makedirs(fpath)                #创建路径
        shutil.copyfile(srcfile,dstfile)      #复制文件
        print ("copy " +srcfile +" -> " +dstfile)
#获取文件下的所有文件夹
def file_name(file_dir):   
    for root, dirs, files in os.walk(file_dir):  
        #print(dirs) #当前路径下所有子目录
        return dirs
#打包pbo文件
def build_pbo(f_arr):
    # cmd = 'cmd.exe d:/start.bat'
    for d in f_arr:
        print ('当前文件夹: %s'% d)
        if os.path.exists(_base_workspace+"map/mission.sqm"):
            os.remove(_base_workspace+"map/mission.sqm")
        else:
            print("文件不存在")
        time.sleep(0.5)
        mycopyfile(_base_workspace+"mission/"+d+"/mission.sqm",_base_workspace+"map/mission.sqm")
        time.sleep(0.5)
        p = subprocess.Popen("PBOConsole.exe -pack " + _base_workspace + "map E:\Missions\Assassination2_1_"+_new_str+"."+d+".pbo", stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
        #curline = p.stdout.readline()
        #while (curline != b''):
        #    print(curline)
        #    curline = p.stdout.readline()
        #p.wait()
        #print(p.returncode)
        time.sleep(0.5)
        if os.path.exists(_base_workspace+"map/mission.sqm"):
            os.remove(_base_workspace+"map/mission.sqm")

def del_file(filepath):
    """
    删除某一目录下的所有文件或文件夹
    :param filepath: 路径
    :return:
    """
    del_list = os.listdir(filepath)
    for f in del_list:
        file_path = os.path.join(filepath, f)
        if os.path.isfile(file_path):
            os.remove(file_path)
        elif os.path.isdir(file_path):
            shutil.rmtree(file_path)


del_file("E:/Missions/")

alter(_base_workspace + "map/Stringtable.xml", _old_str, _new_str)
_file_arr=file_name(_base_workspace+"mission")
build_pbo(_file_arr)
alter(_base_workspace + "map/Stringtable.xml", _new_str, _old_str)

